import { useMessage } from './message';
import { uploadFile } from '/@/api/common'

export interface BasicUploadImageProps {
    accept: string;//文件类型
    multiple: boolean;//是否多选 暂时只做了单个文件上传，多个文件上传的，以后用到添加
    webkitdirectory: boolean;//是否选择文件夹
    isLoading:boolean;//是否正在上传中
    successBack(file:string):void;//成功回调方法
}

export function useUploadIMage(options?: BasicUploadImageProps) {
    const defaultOptions: BasicUploadImageProps = {
        accept: 'image/*',
        multiple: false,
        webkitdirectory: false,
        isLoading: false,
        successBack: function (file: string): void {
            throw new Error('Function not implemented.');
        }
    };
    //合并
    const mergeDefaultOptions = (options: any, props: any): BasicUploadImageProps => {
        for (const key in options) {
            if (!Object.getOwnPropertyDescriptor(props, key)) {
                props[key] = options[key]
            }
        }
        return props
    };
    const state = mergeDefaultOptions(defaultOptions, options);
    //选择文件
    const handleChoiceFile = (callback) => {
        if(state.isLoading){
            callback && callback()
            return useMessage().warning('正在上传中，请等待...')
        }
        let fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = state.accept;
        fileInput.multiple = state.multiple;
        fileInput.webkitdirectory = state.webkitdirectory;
        fileInput.click();
        fileInput.onchange = () => {
            let tempFiles = Array.from(fileInput.files || [])
            beforeUploadFile(tempFiles)
            fileInput.remove()
        }
    };
    //判断文件
    const beforeUploadFile = async (files: any) => {
        if (files.length > 0) {
            state.isLoading = true
            try {
                for (let i = 0; i < files.length; i++) {
                    let file = files[i]
                    let formData = new FormData()
                    formData.append('file',file)
                    const data = await uploadFile(formData)
                    if(data.code == 0){
                        state.isLoading = false
                        state.successBack(data.data.fileUrl)
                    }
                }
            } catch (error) {
                console.log(error, 'upload')
                state.isLoading = false
                useMessage().error('上传失败，请稍后重试！')
            }
        }
    };

    return {
        handleChoiceFile
    }
}